#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QMenu>
#include<QAction>
#include<QMessageBox>
#include<QStack>
#include<cctype>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Sun's Calculator");
    ui->pushButton_and->setText("&&");
    QMenu* pFile=ui->menuBar->addMenu("帮助");
    QAction* pNew=pFile->addAction("关于此计算器");
    QAction* ppNew=pFile->addAction("关于backspace");
    connect(pNew,&QAction::triggered,[=]()
    {
        QMessageBox::about(this,"关于此计算器",""
                                         "此乃数据结构大作业,余制之于庚子年辛巳月庚申日");
    });
    connect(ppNew,&QAction::triggered,[=]()
    {
        QMessageBox::about(this,"关于backspace",""
                                         "单击删除一格，可选中一定量的文本，整体删除");
    });
    string="#";
    ui->textEdit->setReadOnly(true);
    ui->textEdit->setText("请点击按钮输入");
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool priority(QStack<char>&s, char symbol)
{
    if (s.empty() || s.top() == '#' || (s.top() == '('&&symbol!=')' )|| symbol == '(' || symbol=='!') return true;
    if (symbol == '#' || symbol == ')' || s.top() == '!') return false;
    if (symbol == '&')
    {
        if (s.top() == '!')  return false;
        else return true;
    }
    if (symbol == '|')
    {
        if (s.top() == '!'||s.top()=='&')  return false;
        else return true;
    }
    if (symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-');
    {
        if (s.top() == '+' || s.top() == '-') return true;
        else return false;
    }
}

void MainWindow::MutilSymbolError(int num)
{
    char* s=string.toLocal8Bit().data();
    if (!isdigit(s[strlen(s)-2])&&s[strlen(s)-2]!=')')
    {
        QMessageBox::about(this,"输入有误！","您输入的双目运算符无“左值”，已经将您这次操作取消");
        string.chop(1);
        for(int i=1;i<=num;i++)
        ui->textEdit->textCursor().deletePreviousChar();
    }

}

int MainWindow::BracketError()
{
    int nr=0,nl=0;
    for(int i=0;i<string.size();i++)
    {
        if(string[i]=='(') nl++;
        if(string[i]==')') nr++;
    }
    return nl-nr;
}
void MainWindow::DigitalBracketError()
{
    char*s=string.toLocal8Bit().data();
    if(isdigit(s[strlen(s)-1])||s[strlen(s)-1]==')')
    {
        QMessageBox::about(this,"输入有误","您要输入的左括号前是数，您的意思应该是相乘，已经给您添上乘号了");
        string+="*";
        ui->textEdit->textCursor().insertText("*");
    }
}

void MainWindow::BracketDigitalError()
{
    char* s=string.toLocal8Bit().data();
    if(s[strlen(s)-1]==')')
    {
        QMessageBox::about(this,"输入有误","您要输入的数字前是右括号，您的意思应该是相乘，已经给您添上乘号了");
        string+="*";
        ui->textEdit->textCursor().insertText("*");
    }
}

void MainWindow::on_pushButton_equal_released()
{
    if(string=="#")
    {
        QMessageBox::about(this,"输入有误","上来就按个等于号，您是让我输出个寂寞呢！");
        return;
    }
    QStack<double> digital;
    QStack<char> symbol;
    int n=BracketError();
    for(int i=1;i<=n;i++)
    {
        QMessageBox::about(this,"输入有误","您检查一下是否少打了一个右括号，系统已将右括号添置表达式最右端");
        string+=')';
        ui->textEdit->textCursor().insertText(")");
    }
    char* ss=string.toLocal8Bit().data();
    if(!isdigit(ss[strlen(ss)-1])&&ss[strlen(ss)-1]!=')'&&ss[strlen(ss)-1]!='#')
    {
        if(ss[strlen(ss)-1]=='!'&&ss[strlen(ss)-2]=='*')
        {
            QMessageBox::about(this,"输入有误","您计算式的最后两位为运算符，系统已将其去除");
            ui->textEdit->textCursor().deletePreviousChar();
            ui->textEdit->textCursor().deletePreviousChar();
            string.chop(2);
        }
        else
        {
            QMessageBox::about(this,"输入有误","您计算式的最后一位为运算符，系统已将其去除");
            ui->textEdit->textCursor().deletePreviousChar();
            string.chop(1);
        }

    }
    string+="#";
    char*s=string.toLocal8Bit().data();
    int in = 0;
    for (int i = 0; i < strlen(s); i++)
    {
       if (!isdigit(s[i]))
               {
                if (priority(symbol, s[i]))
                    symbol.push(s[i]);
                else
                {
                    if (s[i] == ')'&&symbol.top() == '(')
                    {
                        symbol.pop();
                        continue;
                    }
                    while (!priority(symbol, s[i]))
                    {
                        if (symbol.top() == '!')
                        {
                            double sp = digital.top();
                            digital.pop();
                            if (sp) digital.push(0);
                            else digital.push(1);
                            symbol.pop();
                            continue;
                        }
                        double a = digital.top();
                        digital.pop();
                        double b = digital.top();
                        digital.pop();
                        char c = symbol.top();
                        symbol.pop();
                        switch (c)
                        {
                        case '+':b += a;
                            break;
                        case '-':b -= a;
                            break;
                        case '*':b *= a;
                            break;
                        case'/':b /= a;
                            break;
                        case'&':
                            if (a&&b) b = 1;
                            else b = 0;
                            break;
                        case'|':
                            if (a || b) b = 1;
                            else b = 0;
                        }
                        digital.push(b);
                        if (symbol.top() == '#') break;
                        if (s[i] == '#') continue;
                        if (s[i] == ')'&&symbol.top() == '(')
                        {
                            symbol.pop();
                            break;
                        }
                    }
                    if (s[i] != ')')
                        symbol.push(s[i]);
                }
            }
            else
            {
                int temp = static_cast<int>(s[i] - '0');
                in = in * 10 + temp;
                if (!isdigit(s[i+1]))
                {
                    digital.push(in);
                    in = 0;
                }
            }
        }

     QString result=QString::number(digital.top());
     ui->textEdit->textCursor().insertText("=");
     ui->textEdit->textCursor().insertText(result);
     string+=result;
}

void MainWindow::on_pushButton_1_released()
{

    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="1";
    ui->textEdit->textCursor().insertText("1");
}

void MainWindow::on_pushButton_2_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="2";
    ui->textEdit->textCursor().insertText("2");
}

void MainWindow::on_pushButton_9_released()
{
    if(string=="#")    ui->textEdit->clear();
     BracketDigitalError();
    string+="9";
    ui->textEdit->textCursor().insertText("9");
}

void MainWindow::on_pushButton_3_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="3";
    ui->textEdit->textCursor().insertText("3");
}

void MainWindow::on_pushButton_4_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="4";
    ui->textEdit->textCursor().insertText("4");
}

void MainWindow::on_pushButton_5_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="5";
    ui->textEdit->textCursor().insertText("5");
}

void MainWindow::on_pushButton_6_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="6";
    ui->textEdit->textCursor().insertText("6");
}

void MainWindow::on_pushButton_7_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="7";
    ui->textEdit->textCursor().insertText("7");
}

void MainWindow::on_pushButton_8_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="8";
    ui->textEdit->textCursor().insertText("8");
}

void MainWindow::on_pushButton_0_released()
{
    if(string=="#")    ui->textEdit->clear();
    BracketDigitalError();
    string+="0";
    ui->textEdit->textCursor().insertText("0");
}

void MainWindow::on_pushButton_left_released()
{
    if(string=="#")    ui->textEdit->clear();
    char*s=string.toLocal8Bit().data();
    DigitalBracketError();
    string+="(";
    ui->textEdit->textCursor().insertText("(");

}

void MainWindow::on_pushButton_right_released()
{
    if(string=="#")    ui->textEdit->clear();
    if(!BracketError())
    {
        QMessageBox::about(this,"输入错误","请检查一下左括号数量，系统已将你输入的右括号转换为左括号");
        DigitalBracketError();
        string+="(";
        ui->textEdit->textCursor().insertText("(");
    }
    else
    {
        char*s=string.toLocal8Bit().data();
        if(s[strlen(s)-1]=='(')
        {
            QMessageBox::about(this,"输入错误","您输入右括号后，括号里面没有计算或者数字哦，系统给你补了一个1");
            string+="1";
            ui->textEdit->textCursor().insertText("1");
        }
        string+=")";
        ui->textEdit->textCursor().insertText(")");
    }

}

void MainWindow::on_pushButton_plus_released()
{
    string+="+";
    ui->textEdit->textCursor().insertText("+");
    MutilSymbolError();

}

void MainWindow::on_pushButton_minus_released()
{
    string+="-";
    ui->textEdit->textCursor().insertText("-");
    MutilSymbolError();
}

void MainWindow::on_pushButton_mutiple_released()
{
    string+="*";
    ui->textEdit->textCursor().insertText("*");
    MutilSymbolError();
}

void MainWindow::on_pushButton_divid_released()
{
    string+="/";
    ui->textEdit->textCursor().insertText("/");
    MutilSymbolError();
}

void MainWindow::on_pushButton_Close_released()
{
    close();
}

void MainWindow::on_pushButton_no_released()
{
    if(string=="#")    ui->textEdit->clear();
    char*s=string.toLocal8Bit().data();
    if(isdigit(s[strlen(s)-1])||s[strlen(s)-1]==')')
    {
        QMessageBox::about(this,"输入有误","您要输入的逻辑否符号前是数，您的意思应该是相乘，已经给您添上乘号了");
        string+="*";
        ui->textEdit->textCursor().insertText("*");
    }
    string+="!";
    ui->textEdit->textCursor().insertText("!");
}

void MainWindow::on_pushButton_and_released()
{
    string+="&";
    ui->textEdit->textCursor().insertText("&&");
    MutilSymbolError(2);
}

void MainWindow::on_pushButton_or_released()
{
    string+="|";
    ui->textEdit->textCursor().insertText("||");
    MutilSymbolError(2);
}

void MainWindow::on_pushButton_Clear_released()
{
    string="#";
    ui->textEdit->setText("请点击按钮输入");
}

void MainWindow::on_pushButton__released()
{
    QMessageBox::about(this,"关于此按钮",""
                                     "不知什么原因，&&打出来在按钮上显示的是&，该bug拟后期修复");
}

void MainWindow::on_pushButton_back_released()
{  
    string.chop(1);
    ui->textEdit->textCursor().deletePreviousChar();
    if(string=="#") ui->textEdit->setText("请点击按钮输入");
}
